package com.sky.server.impl;

import cn.hutool.core.bean.BeanUtil;
import com.sky.context.MyThrowLocal;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.server.OrderServer;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Slf4j
@Service
public class OrderServerImpl implements OrderServer {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;


    // 提交订单
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 创建订单pojo往里塞东西
        Orders orders = new Orders();
        BeanUtil.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(1);
        orders.setUserId(MyThrowLocal.getCurrentId());
        orders.setPayStatus(0);
        orders.setOrderTime(LocalDateTime.now());
        orders.setDeliveryStatus(ordersSubmitDTO.getDeliveryStatus());
        orders.setTablewareStatus(1);

        // 填写手机号
        User user = userMapper.getById(MyThrowLocal.getCurrentId());
        // 填地址信息
        AddressBook addressBook = addressBookMapper.getById(orders);
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        //添加下单时间
        orders.setOrderTime(LocalDateTime.now());
        //预计送达时间
        orders.setEstimatedDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());


        // 添加订单，获取订单id给详细列表
        orderMapper.addOrder(orders);

        // 获取购物车，添加详细订单中
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(MyThrowLocal.getCurrentId());
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderMapper.addOrderDetails(orderDetailList);

        // 清空购物车
        shoppingCartMapper.clear(user.getId());
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }

    // 支付订单
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 判断订单状态，和支付方式
        Orders orders = orderMapper.getById(ordersPaymentDTO.getOrderNumber());
        String number = orders.getNumber();
        BigDecimal total = new BigDecimal("0.01");
        String description = orders.getRemark();
        String openid = userMapper.getById(MyThrowLocal.getCurrentId()).getOpenid();

        // 微信支付
        // JSONObject jsonObject = weChatPayUtil.pay(number, total, description, openid);

        //支付成功后修改订单状态，确认支付完需要修改的、订单状态、结账时间、支付方式、支付状态、预计送达时间
        orders.setStatus(2);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(ordersPaymentDTO.getPayMethod());
        orders.setPayStatus(1);
        orderMapper.update(orders);

        return new OrderPaymentVO();
    }

    // 查询历史订单
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 根据当前用户查询历史订单
        Long userId = MyThrowLocal.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        List<Orders> ordersList = orderMapper.historyOrders(ordersPageQueryDTO);

        // 查询订单详情，包装成OrderVO对象返回
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        for (Orders orders : ordersList) {
            OrderVO orderVO = new OrderVO();
            BeanUtil.copyProperties(orders,orderVO);
            List<OrderDetail> orderDetailList = orderMapper.getDetaliById(orders.getId());
            orderVO.setOrderDetailList(orderDetailList);
            orderVO.setOrderDishes("菜品详细信息");

            orderVOS.add(orderVO);
        }

        return new PageResult(ordersList.size(),orderVOS);
    }
}
